<template>
	<view class="page-container" :style="{ height: screenHeight + 'px' }">
		<!-- 顶部Logo区域 -->
		<view class="logo-container" :style="{ height: logoHeight + 'px' }">
			<view class="logo" :style="{ fontSize: logoFontSize + 'px' }">
				<image class="avatar" src="/static/ShortIcon.png"></image>
				Fast Emby
			</view>
		</view>

		<!-- 中间表单区域 -->
		<view class="form-container" :style="{ height: formHeight + 'px' }">
			<uni-forms ref="baseForm" class="custom-form" :model="user" :rules="rules" label-width="22%"
				label-align="left">
				<uni-forms-item :label="$t('serverip')" name="serverip" class="form-item">
					<uni-easyinput v-model="user.serverip" :placeholder="$t('pleaseinput')"
						:style="{ height: inputHeight + 'px', fontSize: inputFontSize + 'px' }" />
				</uni-forms-item>
				<uni-forms-item :label="$t('serverport')" name="serverport" class="form-item">
					<uni-easyinput v-model="user.serverport" type="number" :placeholder="$t('pleaseinput')"
						:style="{ height: inputHeight + 'px', fontSize: inputFontSize + 'px' }" />
				</uni-forms-item>
				<uni-forms-item :label="$t('username')" name="username" class="form-item">
					<uni-easyinput v-model="user.username" :placeholder="$t('pleaseinput')"
						:style="{ height: inputHeight + 'px', fontSize: inputFontSize + 'px' }" />
				</uni-forms-item>
				<uni-forms-item :label="$t('password')" name="password" class="form-item">
					<uni-easyinput v-model="user.password" type="password" :placeholder="$t('pleaseinput')"
						:style="{ height: inputHeight + 'px', fontSize: inputFontSize + 'px' }" />
				</uni-forms-item>
			</uni-forms>
		</view>

		<!-- 底部按钮区域 -->
		<view class="button-container"
			:style="{ height: buttonAreaHeight + 'px', paddingTop: buttonTopPadding + 'px' }">
			<button type="primary" @click="submit('baseForm')" :style="{ 
					height: buttonHeight + 'px', 
					'line-height': buttonHeight + 'px', 
					fontSize: buttonFontSize + 'px',
					borderRadius: buttonRadius + 'px',
					width: buttonWidth + '%'
				}" :disabled="isLoading">
				{{$t('signin')}}
			</button>
		</view>

		<!-- 底部安全区域 -->
		<view class="safe-area-inset" :style="{ height: safeAreaHeight + 'px' }"></view>
	</view>
</template>

<script>
	import request from '@/common/request'
	import store from '@/store/index.js'

	export default {
		name: 'login',
		data() {
			return {
				user: {
					username: "",
					password: "",
					serverip: "",
					serverport: "8096",
					deviceName: "",
					deviceId: "",
					deviceVersion: "",
					userAvatar: "",
					userId: ""
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: 'The username cannot be empty'
						}]
					},
					serverip: {
						rules: [{
							required: true,
							errorMessage: 'The serverip cannot be empty'
						}]
					},
					serverport: {
						rules: [{
							required: true,
							errorMessage: 'The serverport cannot be empty'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: 'The password cannot be empty'
						}]
					}
				},
				// 屏幕尺寸相关变量
				screenHeight: 0,
				safeAreaHeight: 0,

				// 动态计算的尺寸变量
				logoHeight: 0,
				logoFontSize: 0,
				formHeight: 0,
				inputHeight: 0,
				inputFontSize: 0,
				buttonAreaHeight: 0,
				buttonHeight: 0,
				buttonFontSize: 0,
				buttonRadius: 0,
				buttonWidth: 0,
				buttonTopPadding: 0,
				
				// 加载状态控制
				isLoading: false
			}
		},
		onLoad() {
			const systemInfo = uni.getSystemInfoSync()
			this.screenHeight = systemInfo.windowHeight
			this.safeAreaHeight = systemInfo.safeAreaInsets.bottom || 0
			this.calculateDimensions()
		},
		methods: {
			calculateDimensions() {
				const logoRatio = 0.2
				const buttonAreaRatio = 0.18
				
				this.logoHeight = this.screenHeight * logoRatio
				this.buttonAreaHeight = this.screenHeight * buttonAreaRatio
				this.formHeight = this.screenHeight - this.logoHeight - this.buttonAreaHeight - this.safeAreaHeight

				const screenWidth = uni.getSystemInfoSync().windowWidth

				this.logoFontSize = screenWidth * 0.08
				this.inputHeight = screenWidth * 0.12
				this.inputFontSize = screenWidth * 0.038

				this.buttonWidth = 35
				this.buttonHeight = screenWidth * 0.13
				this.buttonFontSize = screenWidth * 0.04
				this.buttonRadius = screenWidth * 0.02
				this.buttonTopPadding = screenWidth * 0.02
			},

			async submit(ref) {
				// 显示加载提示
				uni.showLoading({
					title: '登录中...',
					mask: true // 防止背景点击
				})
				this.isLoading = true

				try {
					const deviceInfo = await this.getDeviceInfo()
					this.user.deviceName = deviceInfo.deviceName
					this.user.deviceId = deviceInfo.deviceId

					await this.$refs[ref].validate()

					store.commit('user', this.user)
					uni.setStorageSync('user', JSON.stringify(this.user))

					try {
						const systemInfo = await request.get('/emby/system/info/public')
						this.user.deviceVersion = systemInfo.Version
					} catch (error) {
						uni.showToast({
							title: '登录失败',
							icon: 'error',
						})
						throw error
					}

					store.commit('user', this.user)
					uni.setStorageSync('user', JSON.stringify(this.user))

					let loginParams = {
						"Username": this.user.username,
						"Pw": this.user.password
					}

					const userinfo = await request.post('/emby/Users/authenticatebyname', loginParams)
					const { AccessToken, User } = userinfo

					this.user.userId = User.Id
					let serverUrl = `${this.user.serverip}:${this.user.serverport}`
					if (!serverUrl.startsWith('http')) {
						serverUrl = `http://${serverUrl}`
					}
					let avatar = `${serverUrl}/emby/Users/${User.Id}/Images/Primary`
					this.user.avatar = avatar

					uni.showToast({
						title: '登录成功',
						icon: 'success',
					})

					store.commit('token', AccessToken)
					store.commit('user', this.user)

					uni.setStorageSync('token', AccessToken)
					uni.setStorageSync('user', JSON.stringify(this.user))

					uni.switchTab({
						url: '/pages/index/index'
					})
				} catch (err) {
					console.log('错误信息：' + JSON.stringify(err))
				} finally {
					// 无论成功失败都关闭加载提示
					uni.hideLoading()
					this.isLoading = false
				}
			},

			getDeviceInfo() {
				const systemInfo = uni.getSystemInfoSync();
				return {
					deviceName: (systemInfo.osName || "Chrome") +"  "+ (systemInfo.deviceModel || ""),
					deviceId: systemInfo.deviceId || 'f31212e4-5ed5-4613-a27f-01afc7d2ca15',
				}
			}
		},
		created() {
			let userTmp1 = uni.getStorageSync('user')
			if (userTmp1) {
				let userTmp = JSON.parse(userTmp1)
				this.user.username = userTmp.username
				this.user.password = userTmp.password
				this.user.serverip = userTmp.serverip
				this.user.serverport = userTmp.serverport
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.page-container {
		position: relative;
		width: 100%;
		overflow: hidden;
		padding: 0 5%;
	}

	.logo-container {
		display: flex;
		justify-content: center;
		align-items: flex-end;
		padding-bottom: 3%;
		
		.avatar{
			width: 60px;
			height: 60px;
		}
	}

	.logo {
		font-weight: bold;
		display: flex;
		align-items: center;
	}

	.form-container {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		overflow: hidden;
	}

	uni-forms {
		width: 100%;

		uni-forms-item {
			margin-bottom: 3%;
			display: flex;
			align-items: center;
		}
	}

	.button-container {
		display: flex;
		justify-content: center;
		width: 100%;
	}

	.custom-form {
		::v-deep .uni-forms-item__label {
			color: #e5e5e5;
			font-weight: 500;
			font-size: 3.6vw;
			padding-right: 2vw;
		}

		::v-deep .uni-easyinput__input {
			color: #1a1a1a;
		}

		::v-deep .uni-easyinput__placeholder {
			color: #999;
		}
	}

	.safe-area-inset {
		width: 100%;
	}
</style>